<template>
  <div style="overflow:hidden">
    <div style="width:1100px;height:140px; margin:0 auto;">
      <el-input v-model="username" placeholder="请输入用户名" @keydown.enter.native="queryUsers()"  style="width:300px;"></el-input>
      <el-button  style="margin-left:10px;" type="primary"  @click="queryUsers()">查询</el-button>
      <el-button  style="float: right;margin-top: 60px; margin-right: 20px;" type="primary" @click="dialogFormVisible0 = true">添加管理员</el-button>
    </div>
    <el-dialog title="添加管理员" :visible.sync="dialogFormVisible0" >
      <el-form :model="userForm0" ref="userForm0" :rules="rules0" >
        <el-form-item label="用户名" >
          <el-input type="text" v-model="userForm0.username"  autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" >
          <el-input type="text" v-model="userForm0.password" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="权限" >
          <el-input type="text" v-model.number="userForm0.role" @keydown.enter.native="addUser()"  autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible0 = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确定</el-button>
      </div>
    </el-dialog>
    <div>
      <el-table
        :data=" username? userInfo : tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
        :show-header="true"
        :height="500"
        :header-cell-style="{background:'#F3F4F7',color:'#555'}"
        style="width: 100%; overflow-y: auto;">
        <el-table-column
          prop="ID"
          label="ID"
          width="100"
          align="center">
        </el-table-column>
        <el-table-column
          prop="username"
          label="账户"
          align="center">
        </el-table-column>
        <el-table-column
          prop="CreatedAt"
          label="创建日期"
          align="center">
        </el-table-column>
        <el-table-column
          prop="role"
          label="权限"
          align="center">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="danger" @click.native.prevent="deleteRow(scope.$inidex, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="编辑信息" :visible.sync="dialogFormVisible" >
        <el-form :model="userForm" ref="userForm" :rules="rules" >
          <el-form-item label="ID" >
            <el-input v-model="userForm.ID" @keydown.enter.native="handleUpdate()"  autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户名" >
            <el-input v-model="userForm.username" @keydown.enter.native="handleUpdate()" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" >
            <el-input v-model="userForm.password" @keydown.enter.native="handleUpdate()" autocomplete="off" ></el-input>
          </el-form-item>
          <el-form-item label="权限" >
            <el-input v-model.number="userForm.role" @keydown.enter.native="handleUpdate()"  autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click.native="handleUpdate()">确 定</el-button>
        </div>
      </el-dialog>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50, 100]"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="tableData.length">
      </el-pagination>
    </div>

  </div>
</template>

<script>
export default {

  name: "UserList",
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      dialogVisiblefile: false,
      formLabelWidth: '80px',
      form: {},
      username: '',
      tableData: [],
      userInfo: [],
      currentPage: 1,
      pageSize: 5,
      dialogFormVisible0: false,
      dialogFormVisible: false,
      userForm: {
        ID: '',
        username: '',
        password: '',
        role: '',
      },
      userForm0: {
        username: '',
        password: '',
        role: ''
      },
      rules: {
        username: [
          {required: true, message: '用户名不能为空', trigger:'blur'},
          {min:4, max: 16, message: '用户名必须在4-16个字符之间', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min:4, max: 16, message: '密码必须在4-16个字符之间', trigger: 'blur'}
        ]
      },
      rules0: {
        username: [
          {required: true, message:"请输入用户名",trigger: "blur"},
          {min:4, max: 16, message: '用户名必须在4-16个字符之间', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min:4, max: 16, message: '密码必须在4-16个字符之间', trigger: 'blur'}
        ],
      },
    }
  },
  methods: {
    async addUser(){
      this.$refs.userForm0.validate(async (valid) => {
        console.log(this.userForm0);
        if(!valid) return this.$message.error('输入非法，请重新输入')
        const {data: res} = await this.$http.post('api/v1/add/user', this.userForm0)
        if (res.code !== 200) return this.$message.error(res.message)
        this.queryUsers()
        this.dialogFormVisible0 = false
        this.userForm0.username=''
        this.userForm0.password=''
        this.userForm0.role=''
      })
    },
    async handleUpdate(){
      this.$refs.userForm.validate(async (valid) => {
        if(!valid) return this.$.message.error("输入非法，请重新输入")
        var id = this.userForm.ID
        const {data: res} = await this.$http.post(`/api/v1/edit/user/${id}`, this.userForm)
        if (res.code !== 200) return this.$message.error(res.message)
        this.$message.success('编辑成功')
        this.dialogFormVisible=false
        this.queryUsers()
      })
    },
    handleEdit(index, row) {
      this.dialogFormVisible = true;//dialog对话窗口打开
      this.userForm = Object.assign({}, row);//将数据传入dialog页面
      this.userForm.index=index;//传递当前index
    },
    deleteRow(index,row) {
      this.$confirm('确认删除？', '提示',{
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then( async ()=>{
        var id = row.ID
        const{data:res} = await this.$http.delete(`api/v1/get/user/${id}`)
        if (res.code===200) {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.queryUsers()
        }
      }).catch(()=>{
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })

    },
    async queryUsers() {
      if (this.username === ''){
        const {data: res} = await this.$http.get('/api/v1/get/users', {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
          },
        })
        if (res.code !== 200) return this.$message.error(res.message)
        console.log(res)
        this.tableData = res.users

      }else{
        var username = this.username
        const{data: res} = await this.$http.get(`/api/v1/get/user/${username}`)

        if (res.code!==200) return this.$message.error(res.message)
        this.userInfo = res.user
      }

    },
    // 每页多少条
    handleSizeChange(val) {
      this.pageSize = val;
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    // 上传文件之前的钩子
    handleBeforeUpload(file){
      if(!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
        this.$notify.warning({
          title: '警告',
          message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
        })
      }
      let size = file.size / 1024 / 1024 / 2
      if(size > 2) {
        this.$notify.warning({
          title: '警告',
          message: '图片大小必须小于2M'
        })
      }
    },
    imageChange(file) {
      console.log('change')
      console.log(file)
      this.form.file = file.raw
      console.log(this.form.file)
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisiblefile = true
    },
    // 重写文件上传方法,覆盖原有的上传方法，将上传的文件依次添加到fileList数组中
    httpRequest(option) {
      this.fileList.push(option)
    },

  }
}
</script>

<style scoped>

</style>
